/**
 * Created by jyd on 2017/7/21.
 */
import Vue from 'vue'
const state = {
  // 人员管理 项目列表
  personProjectList: {},
  // 人员管理 默认项目
  personProjectDefault: {
    pjId: '',
    title: ''
  }
}

// 获取数据
const getters = {
  getPersonProjectList: state => {
    return state.personProjectList
  },
  getPersonProjectDefault: state => {
    return state.personProjectDefault
  }
}

// 转变 更新数据
const mutations = {
  muPersonProjectList (state, payload) {
    const obj = {}
    const lastProject = Vue.prototype.$local.get('lastProject')
    payload.res.forEach((x, i) => {
      if ((lastProject && Number.parseInt(lastProject.key) === x.pjId) || i === 0) {
        Vue.prototype.$store.commit('muPersonProjectDefault', x)
      }
      obj[x.pjId] = x.title
    })
    state.personProjectList = obj
  },
  muPersonProjectDefault (state, payload) {
    state.personProjectDefault.pjId = payload.pjId
    state.personProjectDefault.title = payload.title
  },
  removePersonProjectDefault () {
    state.personProjectDefault.pjId = ''
    state.personProjectDefault.title = ''
  }
}

// 获取数据
const actions = {
  // 从服务端获取项目部列表
  actPersonProjectList ({commit}) {
    return new Promise((resolve) => {
      const currentUser = JSON.parse(Vue.prototype.$getCookie('currentUser'))
      if (currentUser.type === 1) {
        Vue.prototype.$axios({
          method: 'post',
          url: `${Vue.prototype.$site.projectServer}/front/person/findConstructProject.htm`,
          data: Vue.prototype.$qs.stringify({'query.authCheck': 1}, {indices: false})
        }).then(res => {
          if (res.data.errorMsg) {
            resolve(res)
          }
          commit('removePersonProjectDefault')
          commit({
            type: 'muPersonProjectList',
            res: res.data.list
          })
          resolve(res.data.list)
        }).catch(function (err) {
          console.error(err)
        })
      } else {
        commit({
          type: 'muPersonProjectDefault',
          pjId: currentUser.pjId,
          title: currentUser.pjName
        })
        resolve()
      }
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
